package user

import (
	"common/checkImg"
	"common/md5"
	"common/models"
	"common/snowflake"
	"common/validate"
	setting "common/viper"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/docModel"
	"strconv"
)

// Register 用户注册
// @Summary 用户注册
// @Description 验证码-注册用户
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Param object body docModel.UserRegisterReq false "注册参数"
// @Security ApiKeyAuth
// @Success 200 {object} docModel.DocResp
// @Router /user/register [post]
func (h UHandler) Register(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.UserRegisterReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("User:Register with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("User:Register with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//校验验证码
	verify := checkImg.Verify(req.SearchId, req.CheckCode, h.R)
	if !verify {
		resp.SendCode(c, models.CodeImageValidationErr)
		return
	}
	//用户存在否
	exist, _, err := h.M.UserCheckUsername(req.Username)
	if err != nil {
		zap.L().Error("User:h.M.CheckUsernameExist error", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		resp.SendCode(c, models.CodeUserExist)
		return
	}
	//注册用户
	uid := snowflake.GenID()
	userInfo := &models.UserInfo{
		UserID:   strconv.FormatInt(uid, 10),
		Username: req.Username,
		Password: md5.MD5(req.Password),
		NickName: req.NickName,
		ImgHttp:  setting.Conf.MySQLConfig.DefaultImg,
	}
	if err := h.M.UserAdd(userInfo); err != nil {
		zap.L().Error("User: h.M.UserAdd error", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
